package tech.dnf.tripartite.nnfpjss.service.codec;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * Create by dengfan at 2019/8/5 0005 16:43
 */
@Slf4j
public class DESCodec implements Codec<byte[], byte[]> {
    private final static String ALGORITHM = "DES";
    private final Key secretKey;

    public DESCodec(String password) {
        this(password.getBytes());
    }

    public DESCodec(byte[] bs) {
        try {
            DESKeySpec desKeySpec = new DESKeySpec(bs);
            secretKey = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(desKeySpec);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    public DESCodec(Key secretKey) {
        this.secretKey = secretKey;
    }


    public byte[] encrypt(byte[] data) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        return cipher.doFinal(data);
    }

    public byte[] decrypt(byte[] data) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        return cipher.doFinal(data);
    }

    private Cipher getCipher(int mode) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, secretKey);
        return cipher;
    }
}
